package co.saen.nextincloud.beans;

import co.saen.nextincloud.dao.TurnsDAO;
import co.saen.nextincloud.model.Turns;
import co.saen.nextincloud.model.TurnsReasons;
import co.saen.nextincloud.model.Users;
import java.io.Serializable;
import java.util.Date;
import java.util.List;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpServletRequest;

/**
 *
 * @author Felipe Rolvar
 */
@ManagedBean
@SessionScoped
public class TurnsBean implements Serializable {

    private Turns turn;
    private List<Turns> turns;
    private List<TurnsReasons> reasons;
    private int trsCode;

    public int getTrsCode() {
        return trsCode;
    }

    public void setTrsCode(int trsCode) {
        this.trsCode = trsCode;
    }

    public List<TurnsReasons> getReasons() {
        TurnsDAO turnsDAO = new TurnsDAO();
        reasons = turnsDAO.turnReasons();
        return reasons;
    }

    public TurnsReasons selectedReason(int idReason) {
        trsCode = 0;
        TurnsDAO turnsDAO = new TurnsDAO();
        return turnsDAO.searchReasonById(idReason);
    }

    public Turns getTurn() {
        if (turn == null) {
            turn = new Turns();
        }
        return turn;
    }

    public void setTurn(Turns turn) {
        this.turn = turn;
    }

    public TurnsBean() {
    }

    public void askTurn() {
        TurnsDAO turnsDAO = new TurnsDAO();
        turns = turnsDAO.pendingTurns();
        if (turns.isEmpty()) {
            turn.setTrnStat(true);
            turnsDAO.createTurn(turn);
            turns = turnsDAO.pendingTurns();
            turn = turns.get(0);
        } else {
            turn = turns.get(0);
        }
    }

    public void nextTurn() {
        takeTurn();
        turn = new Turns();
        askTurn();
    }

    public void takeTurn() {
        Date trnStart = new Date();
//        turn.setTrnStat(Boolean.TRUE);
        turn.setTrnDateStart(trnStart);
        turn.setUsers((Users) getRequest().getSession().getAttribute("User"));
        TurnsDAO turnsDAO = new TurnsDAO();
        turnsDAO.updateTurn(turn);
    }

    public void finishTurn() {
        Date trnEnd = new Date();
        turn.setTrnDateEnd(trnEnd);
        turn.setTurnsReasons(selectedReason(trsCode));
        TurnsDAO turnsDAO = new TurnsDAO();
        turnsDAO.updateTurn(turn);
        turn = new Turns();
    }

    public static HttpServletRequest getRequest() {
        return (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();
    }
}
